﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;

namespace ViewFormPagesLockDownCustomFeature
{

    public delegate void CodeToRun();

    public class ViewFormPagesLockDownFeatureHandler:SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties receiverProperties)
        {
            ConfirmNotNull(receiverProperties, "receiverProperties");
            ConfirmNotNull(receiverProperties.Feature, "receiverProperties.Feature");
            //ULS.SendTraceTag(ULSTagID.tag_8gzo, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "ViewFormPagesLockDown Feature activation event handled.");
            Debug.WriteLine("ViewFormPagesLockDown Custom Feature activation event handled.");

            try
            {
                SPSite parent = receiverProperties.Feature.Parent as SPSite;
                LockDownViewFormPages(parent, true);
            }
            catch (Exception exception)
            {
                //ULS.SendTraceTag(ULSTagID.tag_8gzp, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Unexpected, "ViewFormPagesLockDown Feature activation failed. Exception: %s.", new object[] { exception.ToString() });
                Debug.WriteLine("ViewFormPagesLockDown Custom Feature activation failed. Exception:" + exception.Message);

                throw;
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties receiverProperties)
        {
            ConfirmNotNull(receiverProperties, "receiverProperties");
            ConfirmNotNull(receiverProperties.Feature, "receiverProperties.Feature");
            //ULS.SendTraceTag(ULSTagID.tag_8gzq, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "ViewFormPagesLockDown Feature deactivation event handled.");
            Debug.WriteLine("ViewFormPagesLockDown Custom Feature deactivation event handled.");

            try
            {
                SPSite parent = receiverProperties.Feature.Parent as SPSite;
                LockDownViewFormPages(parent, false);
            }
            catch (Exception exception)
            {
                //ULS.SendTraceTag(ULSTagID.tag_8gzr, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Unexpected, "ViewFormPagesLockDown Feature activation failed. Exception: %s.", new object[] { exception.ToString() });
                Debug.WriteLine("ViewFormPagesLockDown Custom Feature deactivation failed. Exception:" + exception.Message);
                throw;
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //ULS.SendTraceTag(ULSTagID.tag_8gzs, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "ViewFormPagesLockDown features installing.");
            Debug.WriteLine("ViewFormPagesLockDown Custom features installing.");

        }


        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //ULS.SendTraceTag(ULSTagID.tag_8gzt, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "ViewFormPagesLockDown features uninstalling.");
            Debug.WriteLine("ViewFormPagesLockDown Custom features uninstalling.");

        }

        internal static void ConfirmNotNull(object value, string parameterName)
        {
            if (value == null)
            {
                throw new ArgumentNullException(parameterName);
            }
        }

        internal static void LockDownViewFormPages(SPSite site, bool lockDown)
        {
            RunWithWebCulture(site.RootWeb, delegate
            {
                ConfirmNotCentralAdminWebApp(site.RootWeb);
                SPRoleDefinition byType = site.RootWeb.RoleDefinitions.GetByType(SPRoleType.Guest);
                if (!lockDown)
                {
                    //ULS.SendTraceTag(ULSTagID.tag_8gzv, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "Restoring ViewFormPages right from Limited Access role.");
                    Debug.WriteLine("ViewFormPagesLockDown Custom features Restoring ViewFormPages right from Limited Access role.");

                    byType.BasePermissions |= SPBasePermissions.EmptyMask | SPBasePermissions.ViewFormPages;
                    byType.BasePermissions |= SPBasePermissions.UseRemoteAPIs;
                }
                else
                {
                    //ULS.SendTraceTag(ULSTagID.tag_8gzu, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "Removing ViewFormPages right from Limited Access role.");
                    Debug.WriteLine("ViewFormPagesLockDown Custom features Removing ViewFormPages right from Limited Access role.");

                    byType.BasePermissions &= ~(SPBasePermissions.EmptyMask | SPBasePermissions.ViewFormPages);
                    byType.BasePermissions &= ~SPBasePermissions.UseRemoteAPIs;
                }
                byType.Update();
                //ULS.SendTraceTag(ULSTagID.tag_8gzw, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Medium, "Completed modifying ViewFormPages right for Limited Access role.");
                Debug.WriteLine("ViewFormPagesLockDown Custom features Completed modifying ViewFormPages right for Limited Access role.");
            });
        }

        internal static void ConfirmNotCentralAdminWebApp(SPWeb web)
        {
            ConfirmNotNull(web, "web");
            if (web.Site.WebApplication is SPAdministrationWebApplication)
            {
                //ULS.SendTraceTag(ULSTagID.tag_6wy9, ULSCat.msoulscat_CMS_Provisioning, ULSTraceLevel.Unexpected, "CommonUtilities.ConfirmNotCentralAdminWebApp(): Failed trying to activate publishing sites/features on CentralAdmin Web App. WebUrl: '%s' ", new object[] { web.Url });
                //throw new SPException(GetFormattedString("ErrorPublishingFeaturesDisallowedInCentralAdminWebApplication", new object[] { web.Url }));
                string strException = string.Format(Thread.CurrentThread.CurrentUICulture, "ViewFormPagesLockDownCustomFeature.ViewFormPagesLockDownFeatureHandler - Error: this feature is not allowed in Central Administration Web Application", new object[] { web.Url });
                throw new SPException(strException);
            }
        }

        internal static void RunWithWebCulture(SPWeb web, CodeToRun webCultureDependentCode)
        {
            ConfirmNotNull(web, "web");
            ConfirmNotNull(webCultureDependentCode, "webCultureDependentCode");
            CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
            try
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)web.Language);
                webCultureDependentCode();
            }
            catch
            {
                throw;
            }
            finally
            {
                Thread.CurrentThread.CurrentUICulture = currentUICulture;
            }
        }

        //internal static string GetFormattedString(string resourceName, params object[] args)
        //{
        //    return string.Format(Thread.CurrentThread.CurrentUICulture, GetString(resourceName), args);
        //}
    }
}
